﻿using System.Threading.Tasks;
using Dpx.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace Dpx.ViewModels {
    /// <summary>
    /// 初始化页ViewModel。
    /// </summary>
    public class InitializationPageViewModel : ViewModelBase {
        /******** 构造函数 ********/

        /// <summary>
        /// 诗词存储。
        /// </summary>
        private readonly IPoetryStorage _poetryStorage;

        /// <summary>
        /// 根导航服务。
        /// </summary>
        private readonly IRootNavigationService _rootNavigationService;

        /// <summary>
        /// 收藏存储。
        /// </summary>
        private readonly IFavoriteStorage _favoriteStorage;


        /// <summary>
        /// 初始化页ViewModel。
        /// </summary>
        /// <param name="poetryStorage">诗词存储。</param>
        /// <param name="rootNavigationService">根导航服务。</param>
        /// <param name="favoriteStorage">收藏存储。</param>
        public InitializationPageViewModel(IPoetryStorage poetryStorage,
            IRootNavigationService rootNavigationService,
            IFavoriteStorage favoriteStorage) {
            _poetryStorage = poetryStorage;
            _rootNavigationService = rootNavigationService;
            _favoriteStorage = favoriteStorage;
        }

        /******** 绑定属性 ********/

        /// <summary>
        /// 状态。
        /// </summary>
        public string Status {
            get => _status;
            set => Set(nameof(Status), ref _status, value);
        }

        /// <summary>
        /// 状态。
        /// </summary>
        private string _status;

        /******** 绑定命令 ********/

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ??= new RelayCommand(
                async () => await PageAppearingCommandFunction());

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        internal async Task PageAppearingCommandFunction() {
            if (!_poetryStorage.Initialized()) {
                Status = "正在初始化诗词数据库";
                await _poetryStorage.InitializeAsync();
            }

            if (!_favoriteStorage.Initialized()) {
                Status = "正在初始化收藏数据库";
                await _favoriteStorage.InitializeAsync();
            }

            Status = "所有初始化已完成";
            await Task.Delay(1000);

            await _rootNavigationService.NavigateToAsync(RootNavigationConstant
                .TodayPage);
        }
    }
}